<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="计划日期">
              <a-range-picker @change="onChange" :ranges="{ '本月': [moment(), moment().endOf('month')] }" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" v-action:Query @click="() => { this.$refs.table.refresh() }">查询</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" v-action:Add icon="plus" @click="handleAdd">新建</a-button>
    </div>

    <s-table ref="table" size="default" rowKey="Id" :columns="columns" :data="loadData" showPagination="auto">
      <span slot="status" slot-scope="text, record">
        <template>
          <span v-if="record.Status === 0">编制</span>
          <span v-else-if="record.Status === 1">已下发</span>
          <span v-else-if="record.Status === 2">执行中</span>
          <span v-else-if="record.Status === 3">已完成</span>
          <span v-else-if="record.Status === 4">强制办结</span>
        </template>
      </span>
      <span slot="bom" slot-scope="text, record">
        <template>
          {{ record.Bom.Spec.Desc }}
          <a-divider v-action:Delete type="vertical" />
          {{ record.Bom.Spec.Name }}
          <a-divider v-action:Delete type="vertical" />
          {{ record.Bom.Spec.Code }}
        </template>
      </span>
      <span slot="action" slot-scope="text, record">
        <template v-if="record.Status === 0">
          <a v-action:Update @click="handlePrecollected(record, 1)">预收单</a>
          <a-divider v-action:Delete type="vertical" />
          <a v-action:Update @click="handleStatus(record, 1)">下发</a>
          <a-divider v-action:Delete type="vertical" />
          <a v-action:Update @click="handleEdit(record)">修改</a>
          <a-divider v-action:Delete type="vertical" />
          <a v-action:Delete @click="handleDelete([record])">删除</a>
        </template>
        <template v-else-if="record.Status === 1">
          <a v-action:Update @click="handlePrecollected(record, 1)">预收单</a>
          <a-divider v-action:Delete type="vertical" />
          <a v-action:Update @click="handleStatus(record, 0)">撤回</a>
          <a-divider v-action:Delete type="vertical" />
          <a v-action:Update @click="handleStatus(record, 4)">强制办结</a>
        </template>
        <template v-else>
          <a v-action:Update @click="handlePrecollected(record, 1)">预收单</a>
        </template>
      </span>
    </s-table>
    <EditForm ref="editForm" @Success="() => { this.$refs.table.refresh() }"></EditForm>
    <PrecollectedForm ref="precollectedForm" @Success="() => { this.$refs.table.refresh() }"></PrecollectedForm>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import MainSvc from '@/api/Exec/PlanSvc'
import EditForm from './Edit'
import PrecollectedForm from './Precollected'
import EnumSelect from '@/components/CF/EnumSelect'
import EnumName from '@/components/CF/EnumName'

const columns = [
  { title: '计划日期', dataIndex: 'PlanDate', sorter: true, customRender: (value) => { return moment(value).format('yyyy-MM-DD') } },
  { title: '产品', dataIndex: 'Bom.Product.Name' },
  { title: '规格型号', dataIndex: 'Bom.Name', scopedSlots: { customRender: 'bom' } },
  { title: '计划数量', dataIndex: 'Count' },
  { title: '实际完成', dataIndex: 'Quantity' },
  { title: '计划状态', dataIndex: 'Status', scopedSlots: { customRender: 'status' } },
  { title: '开始时间', dataIndex: 'StartTime' },
  { title: '结束时间', dataIndex: 'EndTime' },
  { title: '操作', dataIndex: 'action', width: '240px', scopedSlots: { customRender: 'action' } }
]

export default {
  components: {
    STable,
    MainSvc,
    EnumSelect,
    EnumName,
    EditForm,
    PrecollectedForm
  },
  data() {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: { StartDate: '', EndDate: '', Keyword: '' },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        var _query = Object.assign({}, { ...this.queryParam })
        for (const key in _query) {
          if (moment.isMoment(_query[key])) {
            _query[key] = _query[key].format('YYYY-MM-DD')
          }
        }
        const requestParameters = Object.assign({ sortField: 'PlanDate', sortOrder: 'desc', Search: _query }, parameter)
        console.log('loadData request parameters:', requestParameters)
        return MainSvc.GetPage(requestParameters)
      },
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
  },
  created() { },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    moment,
    handleAdd() {
      this.mdl = null
      this.visible = true
      this.$refs.editForm.openForm(null, '新增')
    },
    handlePrecollected(record) {
      this.visible = true
      this.mdl = { ...record }
      this.$refs.precollectedForm.openDrawer(record)
    },
    handleStatus(record, status) {
      if (status === 1) {
        MainSvc.Issue(record).then(result => {
          this.loading = false
          if (result.Success) {
            record.status = status
            MainSvc.Save(record).then(result => {
              this.loading = false
              if (result.Success) {
                this.$refs.table.refresh()
              } else {
                this.$message.error(result.Msg)
              }
            })
          } else {
            this.$message.error(result.Msg)
          }
        })
      } else if (status === 0) {
        MainSvc.RollBackPlanIssue(record.Id).then(result => {
          if (result.Success) {
            this.$refs.success('操作成功!')
            this.$refs.table.refresh()
          } else {
            this.$refs.error(result.Msg)
          }
        })
      } else {
        record.status = status
        MainSvc.Save(record).then(result => {
          this.loading = false
          if (result.Success) {
            this.$refs.table.refresh()
          } else {
            this.$message.error(result.Msg)
          }
        })
      }
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
      this.$refs.editForm.openForm(record.Id, '修改')
    },
    onChange(dates, dateStrings) {
      this.queryParam.StartDate = dateStrings[0]
      this.queryParam.EndDate = dateStrings[1]
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm() {
      this.queryParam = { Keyword: '' }
    },
    handleDelete(rows) {
      var thisObj = this
      var ids = rows.map(value => value.Id)
      this.$confirm({
        title: '确认删除吗?',
        onOk() {
          return new Promise((resolve, reject) => {
            MainSvc.Delete(ids).then(result => {
              resolve()
              if (result.Success) {
                thisObj.$message.success('操作成功!')
                thisObj.$refs.table.refresh()
              } else {
                thisObj.$message.error(result.Msg)
              }
            })
          })
        }
      })
    }
  }
}
</script>
